package amq.consumers;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class TestConsumer {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		if(args.length==0)
		{
			System.out.printf("\t[Info] Please give Connector URI! (ex 'tcp://localhost:61616')\n");
			return;
		}
		boolean isStop = false;
		ConnectionFactory connectionFactory;  
        Connection connection = null;  
        Session session = null;  
        Destination destination;  
        MessageConsumer consumer = null;  
        Message message = null;  
        boolean useTransaction = false;  
        try {  
            connectionFactory = new ActiveMQConnectionFactory(args[0]);  
            connection = connectionFactory.createConnection();  
            connection.start();  
            session = connection.createSession(useTransaction,  
                    Session.AUTO_ACKNOWLEDGE);  
            destination = session.createQueue("TEST.QUEUE");  
            consumer = session.createConsumer(destination);  
            System.out.printf("\t[Info] Consumer starting...\n");
            while(!isStop)
            {
            	message = (TextMessage) consumer.receive(1000);  
                if(message!=null) {
                	System.out.printf("\tReceived message:\n%s\n", message);                	
                	if(((TextMessage)message).getText().equals("stop")) isStop=true;
                	//if(message.getStringProperty("text").equals("stop")) isStop=true;
                }
                
            }
            System.out.printf("\t[Info] Consumer exit...Bye!\n");
        } catch (JMSException jmsEx) {  
  
        } finally {  
            consumer.close();  
            session.close();  
            connection.close();  
        }  
	}
}
